package org.monkeypuzzler.css;

import org.json.JSONException;

import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.SeleniumException;

/**
 * The Recorder is a testing tool that attempts to make it easy to verify the position and dimensions of an Element.
 * @author csmith
 */
public class Recorder 
{
	final Selenium selenium;
	final PersistenceStrategy persistor;
	
	
	/**
	 * 
	 * 
	 * @param selenium The remote control for the current test
	 * @param elementDir The directory of where to save elements for the current test
	 */
	public Recorder( Selenium selenium, PersistenceStrategy persistor ) 
	{
		this.selenium = selenium;
		this.persistor = persistor;
	}
	/**
	 * Explicitly stores an element to storage
	 * @param locator A selenium locator string, to find the element
	 * @param id String locator, String identifier
	 * @return
	 */
	public Element store(String locator, String id) throws JSONException,SeleniumException
	{
		Element element = Element.getElement(this.selenium, locator);
		this.persistor.store(locator, id, element);
		return element;
	}
	
	/**
	 * Explicitly retrieves an Element
	 * @param locator A selenium locator string, to find the element
	 * @param id A unique identifier for the current Element state.
	 * @return
	 */
	public Element retrieve(String locator, String id)
	{
		return this.persistor.retrieve(locator, id);
	}
	
	/**
	 * The workhorse method.
	 * If a given locator and id are not stored, they will be.
	 * If they are stored, then element will 
	 * @param locator A selenium locator string, to find the element
	 * @param id String locator, String identifier
	 * @return
	 */
	public void assertElement(String locator, String id) throws JSONException, SeleniumException, AssertionError
	{
		if (this.persistor.exists(locator, id))
		{
			Element expectation = this.persistor.retrieve(locator, id);
			Element test = Element.getElement(this.selenium, locator);
			if (!expectation.equals(test))
			{
				//should write a compare function on element that return a list of mismatches.
				StringBuilder err = new StringBuilder();
				err.append("The element: \n\t locator [").append(locator).append("]")
					.append("\n\t id [").append(id).append("]")
					.append("\nIs not styled correctly:")
					.append("\n\texpected [").append(expectation).append("]")
					.append("\n\twas [").append(test).append("]");
					
				throw new AssertionError(err.toString());
			}
		}
		else
			//fall back to recording.
			this.store(locator, id);
	}
}
